import handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author zy.jordan
 */
public class NettyServer {
  public static void main(String[] args) {
    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    NioEventLoopGroup workGroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap
        .group(bossGroup, workGroup)
        .channel(NioServerSocketChannel.class)
        .childHandler(new ChannelInitializer<NioSocketChannel>() {
          @Override
          protected void initChannel(NioSocketChannel nioSocketChannel) {
            nioSocketChannel.pipeline().addLast(new PacketDecoder());
            nioSocketChannel.pipeline().addLast(new LoginRequestHandler());
            nioSocketChannel.pipeline().addLast(new MessageRequestHandler());
            nioSocketChannel.pipeline().addLast(new PacketEncoder());
          }
        });
    bind(serverBootstrap, 1527);
  }

  private static void bind(final ServerBootstrap serverBootstrap, final int port) {
    serverBootstrap.bind(port).addListener(future -> {
      if (future.isSuccess()) {
        System.out.println("端口绑定成功 : " + port);
      } else {
        System.out.println("端口绑定失败 : " + port);
        bind(serverBootstrap, port + 1);
      }
    });
  }
}
